# -*- coding:utf-8 -*-
"""
@File : sim_mul_PGM6248

@Author: 爸爸

@Date : 2019-11-04

@Desc :模拟器PGM6248多设备，随机发送DAT ，ALM， ERR
"""

import random
import socket
import struct
import threading
import time

flags = [b"DAT", b"ERR", b"ALM"]
lenListener = 10  # 监听队列长度，1已经够用
sendInterval = 10  # 发送时间间隔，默认为3s
address = [("127.0.0.1", 9250), ("10.11.5.34", 6100), ("10.11.5.34", 6200), ("10.11.5.34", 6300)]
sc_list = []


def createData(ip):
    flag = random.choice(flags)
    co = random.randint(0, 200)
    h2s = random.randint(0, 200)
    hcn = random.randint(0, 200)
    lel = random.randint(0, 200)
    voc = random.randint(0, 200)
    gammar = random.randint(0, 200)
    msg = " {} co:{}; h2s:{}; hcn:{}; lel:{}; voc:{}; gammar:{}".format(flag, co, h2s, hcn, lel, voc, gammar)
    print(msg)
    a, b, c, d, e, f, g, h, i, j, k, l = struct.pack("<HHHHHH", co, h2s, hcn, lel, voc, gammar)
    ips = [int(i) for i in ip.split('.')]
    res = [flag[0], flag[1], flag[2], ips[0], ips[1], ips[2], ips[3], a, b, c, d, e, f, g, h, i, j, k, l, 1] * 3
    # ls = [
    #     0x44, 0x41, 0x54, 0xc0, 0xa8, 0x01, 0xc8, 0x00, 0x00, 0x00, 0x00, 0xbc, 0x00, 0x00, 0x00, 0xff, 0xff, 0x05,
    #     0x00, 0xf0,
    #     0x44, 0x41, 0x54, 0xc0, 0xa8, 0x01, 0xc8, 0x00, 0x00, 0x00, 0x00, 0xbc, 0x00, 0x00, 0x00, 0xff, 0xff, 0x05,
    #     0x00, 0xf0,
    #     0x44, 0x41, 0x54, 0xc0, 0xa8, 0x01, 0xc8, 0x00, 0x00, 0x00, 0x00, 0xbc, 0x00, 0x00, 0x00, 0xff, 0xff, 0x05,
    #     0x00, 0xf0,
    # ]
    return bytes(res), msg


def receive(sc, address):
    while True:
        try:
            conn, addr = sc.accept()
            while True:
                data, msg = createData(address[0])
                conn.sendall(data)
                print(address, msg)
                time.sleep(sendInterval)
        except Exception as e:
            print(e)


def main():
    # createData()
    for t in address:
        sc = socket.socket()
        sc.bind(t)
        sc.listen(lenListener)
        threading.Thread(target=receive, args=(sc, t)).start()


if __name__ == '__main__':
    main()
    pass
